package com.wolfsea.launcherdemo
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.*
import androidx.core.view.get
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

/**
 *@desc LauncherLayout
 *@author liuliheng
 *@time 2022/12/16  0:17
 **/
class LauncherLayout2 @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : ViewGroup(context, attributeSet), CoroutineScope by MainScope(), PagingScrollHelper.OnPageChangeListener {

    private val circlesDistance = context.resources.getDimension(R.dimen.dp_5)
    private val horizontalSpace = context.resources.getDimension(R.dimen.dp_20).toInt()

    private var pageCount = 0
    private var currentPage = 0

    private val selectedPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            style = Paint.Style.FILL
            strokeWidth = context.resources.getDimension(R.dimen.dp_1)
            color = context.resources.getColor(R.color.purple_200)
        }
    }

    private val unSelectedPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            style = Paint.Style.FILL
            strokeWidth = context.resources.getDimension(R.dimen.dp_1)
            color = context.resources.getColor(R.color.purple_500)
        }
    }

    private val mRecyclerView: RecyclerView

    init {
        inflate(context, R.layout.launcher_item_layout, this)
        mRecyclerView = findViewById(R.id.launcher_item_rv)
    }

    override fun onFinishInflate() {
        super.onFinishInflate()

        val contentDataList = mutableListOf<ContentData>()

        val dataArray = arrayOf(
            "统信软件",
            "鲲鹏",
            "创新中心",
            "工具",
            "应用范围",
            "递归",
            "嵌套",
            "进程",
            "性能",
            "最大限度",
            "循环",
            "汇编代码",
            "重要",
            "事实上",
            "编写",
            "六个月",
            "优惠券",
            "安装",
            "鲜明对比",
            "应用商店",
            "调查",
            "芯片",
            "可能",
            "消息",
            "相关人士",
            "关系部门",
            "投资人",
            "暴雪",
            "解决方案",
            "发布",
            "是编程中",
            "重要",
            "概念",
            "高级语言",
            "得到",
            "广泛",
            "应用",
            "硬件层",
            "实现",
            "重要性",
            "不言而喻",
            "但是",
            "现代编程",
            "许多",
            "语言",
            "完全可以",
            "使用循环",
            "我们",
            "利用",
            "函数",
            "映射",
            "解析式",
            "实现",
            "相同",
            "功能",
            "但是",
            "情况下",
            "关键字",
            "关键字",
            "跳过",
            "元素",
            "加快",
            "目前",
            "可用模型",
            "还不够好",
            "不足以",
            "生命科学",
            "领域",
            "重大影响",
            "科学家",
            "都说",
            "只能",
            "只能",
            "情况下",
            "发挥些许",
            "作用",
            "基因组",
            "前景的",
            "应用方向",
            "尚属",
            "起步阶段",
            "看好",
        )

        for (item in dataArray) {
            contentDataList.add(ContentData(R.mipmap.ic_launcher, item))
        }

        val scrollHelper = PagingScrollHelper()
        scrollHelper.setUpRecyclerView(mRecyclerView)
        scrollHelper.setOnPageChangeListener(this)
        scrollHelper.updateLayoutManager()
        //默认滑动到第一页
        scrollHelper.scrollToPosition(0)
        val horizontalPageLayoutManager =
            HorizontalPageLayoutManager(
                context,
                6,
                4
            )
        mRecyclerView.isHorizontalScrollBarEnabled = true
        mRecyclerView.layoutManager = horizontalPageLayoutManager
        mRecyclerView.adapter = LauncherPageRvAdapter(contentDataList)

        pageCount = if (dataArray.size % BaseConstant.ITEMS_PER_PAGE == 0) {
            dataArray.size / BaseConstant.ITEMS_PER_PAGE
        } else {
            dataArray.size / BaseConstant.ITEMS_PER_PAGE + 1
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        for (i in 0.until(childCount)) {
            val child = get(i)
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0)
        }

        setMeasuredDimension(
            MeasureSpec.getSize(widthMeasureSpec) - paddingStart - paddingEnd,
            MeasureSpec.getSize(heightMeasureSpec) - paddingTop - paddingBottom
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        for (i in 0.until(childCount)) {
            val child = get(i)
            val childMeasuredWidth = child.measuredWidth
            val childMeasuredHeight = child.measuredHeight

            val cl = childMeasuredWidth * i
            val ct = 0
            val cr = cl + childMeasuredWidth
            val cb = childMeasuredHeight

            child.layout(
                cl,
                ct,
                cr,
                cb
            )
        }
    }

    override fun dispatchDraw(canvas: Canvas?) {
        super.dispatchDraw(canvas)
        if (pageCount > 1) {
            val cy = this.measuredHeight.toFloat() * 4 / 5
            /*
             * 圆形指示器
             * */
            for (i in 0.until(pageCount)) {
                canvas?.drawCircle(
                    calculatePointIndicatorX(i),
                    cy,
                    circlesDistance,
                    if (currentPage == i) selectedPaint else unSelectedPaint
                )
            }
        }
    }


    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()
        return get(0).onTouchEvent(event)
    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }

    override fun onPageChange(index: Int) {
        currentPage = index
        invalidate()
    }

    /*计算圆形指示器的x轴坐标*/
    private fun calculatePointIndicatorX(pageIndex: Int): Float {
        return if (pageCount % 2 == 0) {
            val middleValue = pageCount / 2
            val space = when {
                pageIndex == middleValue - 1 -> {
                    -horizontalSpace / 2
                }
                pageIndex == middleValue -> {
                    horizontalSpace / 2
                }
                pageIndex < middleValue - 1 -> {
                    (pageIndex - (middleValue - 1)) * horizontalSpace - horizontalSpace / 2
                }
                pageIndex > middleValue -> {
                    (pageIndex - middleValue) * horizontalSpace + horizontalSpace / 2
                }
                else -> {
                    0
                }
            }
            measuredWidth.toFloat() / 2 + space.toFloat()
        } else {
            measuredWidth.toFloat() / 2 + (pageIndex - pageCount / 2) * horizontalSpace
        }
    }

    fun getCurrentPage(): Int = currentPage

    companion object {
        const val TAG = "LauncherLayout"
    }

}